參考文件:
使用指令安裝:
composer require spatie/laravel-permission
php artisan vendor:publish --provider="Spatie\Permission\PermissionServiceProvider"
並使用 migrate
php artisan migrate
則需要修改自動生成的 migration create_permission_tables.php
,把 model_morph_key
原先的 unsignedBigInteger 改成 string:
Schema::create($tableNames['model_has_roles'], function (Blueprint $table) use ($tableNames, $columnNames, $teams) {
$table->unsignedBigInteger(PermissionRegistrar::$pivotRole);
$table->string('model_type');
// $table->unsignedBigInteger($columnNames['model_morph_key']);
$table->string($columnNames['model_morph_key']);
在自己的 Model 下也要確認是否有設置好:
protected $primaryKey = 'id';
public $incrementing = false;
protected $keyType = 'string';
如果沒設定好,在 model_has_roles
表中的 model_id
會為 0,正確應為身份組 Model 的 id。
假設使用 Seeder 建立初始的身份與權限:
php artisan make:seeder CreateRole
找到建立的 datebase/seeders/CreateRole.php
:
use Spatie\Permission\Models\Role;
use Spatie\Permission\Models\Permission;
...
public function run()
{
app()[\Spatie\Permission\PermissionRegistrar::class]->forgetCachedPermissions();
Permission::create(['name' => 'edit articles']);
Permission::create(['name' => 'delete articles']);
Permission::create(['name' => 'publish articles']);
Permission::create(['name' => 'unpublish articles']);
$role = Role::create(['name' => 'writer']);
$role->givePermissionTo(Permission::all());
}
如果是多個 guards 則需要加上 guard_name
,否則會使用 auth.gurads 的第一個做為預設:
Permission::create(['guard_name' => 'store', 'name' => 'unpublish articles']);
$role = Role::create(['guard_name' => 'store', 'name' => 'writer']);
假設我們已經找到目標的 $user :
// 新增
$user->assignRole('writer');
$user->assignRole('writer', 'admin');
$user->assignRole(['writer', 'admin']);
// 同步(會刪掉原本的,使權限跟同步的一致)
$user->syncRoles(['writer', 'admin']);
// 刪除
$user->removeRole('writer');
// 檢查
$user->hasRole('writer');
$user->hasRole(['editor', 'moderator']);
假設我們已經找到目標的 $user :
$user->can('edit articles');
$user->hasPermissionTo('edit articles');
$user->hasAllPermissions(['edit articles', 'publish articles', 'unpublish articles']);
修改 config/permission.php
:
'enable_wildcard_permission' => true,
建立權限:
Permission::create('name' => 'posts']);
Permission::create('name' => 'posts.create']);
Permission::create('name' => 'posts.read']);
Permission::create('name' => 'posts.update']);
Permission::create('name' => 'posts.delete']);
// 建立一個有全部權限的Role
$role = Role::create('name' => 'admin']);
$role->givePermissionTo('posts');
// 建立一個只能 read 的Role
$role = Role::create('name' => 'reader']);
$role->givePermissionTo('posts.read');
驗證:
$user->syncRoles('admin');
$user->can('posts'); // true
$user->can('posts.create'); // true
$user->can('posts.read'); // true
$user->can('posts.xxxx'); // true
$user->syncRoles('reader');
$user->can('posts'); // false
$user->can('posts.create'); // false
$user->can('posts.read'); // true
$user->can('posts.xxxx'); // false